package com.sqoop.client.client;

import com.sqoop.commons.send.IClient;
import com.sqoop.commons.send.impl.JmsClient;
import com.sqoop.core.MsgFutrue.MsgFutrue;
import com.sqoop.core.futruecache.FutureCache;
import com.sqoop.core.request.Request;
import com.sqoop.core.request.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


/**
 * Created by zw on 2017/11/6.
 */
public class MsgClient implements IClient {
    private static Logger logger = LogManager.getLogger(MsgClient.class.getName());

    private IClient client  = new JmsClient();

    private int timeout = 30;
    //private IReceiver receiver;

    private FutureCache futureCache;

    @Override
    public Response send(Request request) {
        //request.getReceiver();
        MsgFutrue futrue = new MsgFutrue(request);
        futureCache.save(request.getMsgid(),futrue);
        client.send(request);
        logger.info("send a request,id is {} ",request.getMsgid());
        try {
            Response response =  futrue.get(timeout, TimeUnit.SECONDS);
            return response;
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(e);
        } catch (ExecutionException e) {
            e.printStackTrace();
            logger.error(e);
        } catch (TimeoutException e) {
            e.printStackTrace();
            logger.error(e);
        }

        return null;
    }

    public FutureCache getFutureCache() {
        return futureCache;
    }

    public void setFutureCache(FutureCache futureCache) {
        this.futureCache = futureCache;
    }

    public MsgClient(IClient client, FutureCache futureCache) {
        this.client = client;
        this.futureCache = futureCache;
    }
}